# -*- coding: utf-8 -*-

import unittest
from traffic.models import UserProfile, Payment, TrafficCategory, Tariff, \
    TariffRule, PrepaidPacket
from django.contrib.auth.models import User
import datetime

mb = 1024*1024

class MyTestCase(unittest.TestCase):
    def setUp(self):
        # очищаем
        for i in User, UserProfile,Tariff, TariffRule, TrafficCategory, \
                 PrepaidPacket:
            i.objects.all().delete()
        self.kreved = User(username="kreved")
        self.kreved.save()
        self.inet = TrafficCategory(name=u"интернет")
        self.inet.save()
        self.basic = Tariff(name="Basic")
        self.basic.save()
        self.p1 = Tariff(name="P1", cost=6)
        self.p1.save()
        self.br = TariffRule(traffic_category=self.inet, \
            excess_price=0.04, tariff=self.basic)
        self.pr = TariffRule(traffic_category=self.inet, \
            excess_price=0.01, tariff=self.p1, packet=1024*mb) # 1GB
        self.vasja = User(username="test") # username is important for testKey
        self.vasja.save()
        self.kp = UserProfile(user=self.kreved, ip="192.168.0.10", \
            tariff=self.basic)
        self.vp = UserProfile(user=self.vasja, ip="192.168.0.17", \
            tariff=self.basic)
        for i in self.kreved, self.inet, self.basic, self.vasja, self.kp, \
                 self.vp, self.pr:
            i.save()
        self.vp.update_firewall = lambda x=1: x
        self.kp.update_firewall = lambda x=1: x
            
    def testKey(self):
        self.vasja.set_password('test')
        self.vp.update_key('test')
        key = self.vp.key
        self.assertEquals(key, '8b069ec7eca4dec0349b1238070704a4176af176');
        self.vasja.set_password('secret2')
        self.vp.update_key('secret2')
        key = self.vp.key
        self.assertEquals(key, 'e88bb58e6d39fa256a5f3b38083a8d86ded07a55');
        
    def testPayment(self):
        self.assertEquals(self.br.tariff, self.basic)
        self.assertEquals(self.vp.balance, 0)
        self.vp.turn_inet(True)
        self.vp.pay(2, cashier=self.kp, category=None, comment="")
        self.vp.check()
        self.assertEquals(self.vp.balance, 2)
        self.assertEquals(self.vp.inet, True)
        self.assertEquals(self.vp.blocked, False)
        self.vp.pay(-3, cashier=self.kp)
        self.vp.check()
        self.assertEquals(self.vp.balance, -1)
        self.assertEquals(self.vp.blocked, True)
        self.assertEquals(self.vp.inet, False)

    def testTariff(self):
        self.vp.balance = 100
        self.vp.change_tariff(self.basic, clear=True)
        self.vp.check()
        self.assertEquals(self.vp.tariff, self.basic)
        self.failIf(self.vp.prepaidpacket_set.all())
        self.vp.change_tariff(self.p1, False)
        self.vp.check()
        self.failIf(self.vp.prepaidpacket_set.all().count() == 0, \
            "check() не создаёт нужные prepaid пакеты")
        self.assertEquals(self.vp.prepaidpacket_set.get(traffic_category=\
            self.inet).prepaid, 1024*mb)

    def testTrafficHandling(self):
        self.vp.balance = 10
        self.vp.change_tariff(self.p1, True)
        self.vp.check()
        
        # 10-6=4 грн на счету, 1GB интернета
        self.vp.handle_traffic(datetime.date(2000, 1, 3), 0, self.inet, [500*mb, 0])
        self.assertEquals(self.vp.balance, 4)
        self.assertEquals(self.vp.prepaidpacket_set.get(traffic_category=\
            self.inet).prepaid, 524*mb)
        self.vp.save()
        self.vp.check()
        
        # обратить внимание на True в конце
        self.vp.handle_traffic(datetime.date(2000, 1, 3), 0, self.inet, [500*mb, 0], True)
        self.assertAlmostEqual(self.vp.balance, 4, 2)
        self.assertEquals(self.vp.prepaidpacket_set.get(traffic_category=\
            self.inet).prepaid, 524*mb)
        self.vp.save()
        self.vp.check()
        
        self.vp.handle_traffic(datetime.date(2002, 1, 3), 0, self.inet, [500*mb, 0])
        self.assertAlmostEqual(self.vp.balance, 4, 2)
        self.assertEquals(self.vp.prepaidpacket_set.get(traffic_category=\
            self.inet).prepaid, 24*mb)
        self.vp.save()
        self.vp.check()

        # 24 мегабайта из пакета, и 276 - платно, по 0.1 копейки == 2.76 грн.
        self.vp.handle_traffic(datetime.date(2002, 1, 3), 0, self.inet, [300*mb, 0])
        self.assertAlmostEqual(self.vp.balance, 4-2.76, 2)
        self.vp.save()
        self.vp.check()

        # все 300 мб. - платно, == 3 грн.
        self.vp.handle_traffic(datetime.date(2002, 1, 3), 0, self.inet, [300*mb, 0])
        self.assertAlmostEqual(self.vp.balance, 4-2.76-3.00, 2)
        self.vp.save()
        self.vp.check()

        # self.vp.check() должна была заблокировать юзера, т.к. баланс отрицательный
        self.failIf(self.vp.inet)
        self.assert_(self.vp.blocked)

    def testTurnInet(self):
        self.vp.balance = 10
        self.vp.change_tariff(self.basic, True)
        self.vp.check()
        self.vp.turn_inet(True)
        self.vp.check()
        self.assert_(self.vp.inet)
        self.vp.inet_until = datetime.datetime.fromtimestamp(0)
        self.vp.check()
        self.failIf(self.vp.inet, "интернет не выключается автоматом")
        cur = datetime.datetime.now()
        delta = datetime.timedelta(days=30)
        self.vp.turn_inet(True, delta)
        self.assertEquals((cur+delta).date(), self.vp.inet_until.date())
        delta = datetime.timedelta(days=3)
        self.vp.turn_inet(True, delta)
        self.assertEquals((cur+delta).date(), self.vp.inet_until.date())

    def test_select_for_update(self):
        UserProfile.objects.select_for_update()
